from fastapi import APIRouter, Depends
from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from modules.system.schemas.dept_schemas import DeptCreate, DeptUpdate
from modules.system.params.dept_params import DeptQuery
from modules.system.services.dept_service import DeptService
from modules.system.vos.dept_vo import DeptResponse, DeptListResponse, DeptTreeResponse, DeptTreeNode
from core.pagination import DependsPagination, PageData

router = APIRouter()


@router.post("/create", response_model=ApiResponse[DeptResponse], summary="创建事业部")
async def create_dept(payload: DeptCreate, db: AsyncSession = Depends(get_db)):
    dept = await DeptService.create_dept(db, payload)
    return api_success(DeptResponse.model_validate(dept), msg="创建成功")


@router.post("/list", 
    response_model=ApiResponse[PageData[DeptResponse]],
    summary="获取事业部列表",
    dependencies=[DependsPagination],
)
async def list_depts(query_params: DeptQuery, db: AsyncSession = Depends(get_db)):
    result = await DeptService.get_depts_with_pagination(db, query_params)
    return api_success(data=result, msg="获取成功")


@router.put("/{dept_id}", response_model=ApiResponse[DeptResponse], summary="更新事业部")
async def update_dept(dept_id: int, payload: DeptUpdate, db: AsyncSession = Depends(get_db)):
    dept = await DeptService.update_dept(db, dept_id, payload)
    return api_success(data=dept, msg="更新成功")


@router.delete("/{dept_id}", response_model=ApiResponse[dict], summary="删除事业部")
async def delete_dept(dept_id: int, db: AsyncSession = Depends(get_db)):
    await DeptService.delete_dept(db, dept_id)
    return api_success({"message": f"事业部ID {dept_id} 删除成功"}, msg="删除成功")


@router.get("/tree", response_model=ApiResponse[DeptTreeResponse], summary="获取事业部树")
async def get_dept_tree(status: bool | None = None, db: AsyncSession = Depends(get_db)):
    items = await DeptService.get_dept_tree(db, status=status)
    nodes = [DeptTreeNode.model_validate(i) for i in items]
    return api_success(DeptTreeResponse(items=nodes), msg="获取成功")

@router.get("/{dept_id}", response_model=ApiResponse[DeptResponse], summary="根据ID获取事业部")
async def get_dept_by_id(dept_id: int, db: AsyncSession = Depends(get_db)):
    dept = await DeptService.get_dept_by_id(db, dept_id)
    return api_success(data=dept, msg="获取成功")

@router.get("/code/{dept_code}", response_model=ApiResponse[DeptResponse], summary="根据编码获取事业部")
async def get_dept_by_code(dept_code: str, db: AsyncSession = Depends(get_db)):
    dept = await DeptService.get_dept_by_code(db, dept_code)
    return api_success(data=dept, msg="获取成功")